package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ciei.dpagm.common.converter.JsonConverter;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.Area;
import com.ciei.dpagm.entity.Company;
import com.ciei.dpagm.mapper.CompanyMapper;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.ConvertUtil;
import com.ciei.dpagm.util.JsonUtil;
import com.ciei.dpagm.util.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class CompanyService extends BaseService<CompanyMapper,Company> {
	private AutoCodeSeedService autoCodeSeedService;
	private JSONObject json;

	@Autowired
	private AreaService areaService;

	@Autowired
	private CompanyMapper companyMapper;
	
	@Resource(name = "autoCodeSeedService")
	public void setAutoCodeSeedService(AutoCodeSeedService autoCodeSeedService) {
		this.autoCodeSeedService = autoCodeSeedService;
	}


	/**
	 * 获取厂家名称
	 *
	 * @param companyId 厂家Id
	 * @return 厂家名称
	 * @author kiho
	 * @date 2019/12/17
	 */
	public String getCompanyName(Integer companyId){
		return companyMapper.getCompanyName(companyId);
	}


	/**
	 * 新增或修改公司信息
	 * @param jsonObject
	 * @return
	 */
	public JSONObject addOrUpdateVue(JSONObject jsonObject,String type) {
		JSONObject json = null;
		String[] propertyNames = {"companyName","isDelete","kind"};
		Object[] values = {jsonObject.getString("companyName"),0,0};
		List<Company> companyList=new ArrayList<>();
		if("add".equals(type)){
			companyList=findByProperties(propertyNames, values);
			if(companyList.size()>0){
				json = JsonUtil.getFail("公司已存在,添加失败!");
			}
		}else{
			companyList=findByPropertiesNotSelf(propertyNames, values, jsonObject.getInteger("companyId"));
			if(companyList.size()>0){
				json = JsonUtil.getFail("公司已存在,更新失败!");
			}
		}
		if(companyList.size()==0 ) {
			JsonConverter<Company> jsonConverter = new JsonConverter<>();
			Company company = new Company();
			company = jsonConverter.convert(jsonObject, company);
			if (jsonObject.getInteger("countryId") != null) {
				Integer countryId = jsonObject.getInteger("countryId");
				List<Area> countryAreas = areaService.findByProperty("areaId", countryId);
				company.setCountry(countryAreas.get(0).getAreaName());
				company.setAreaCode(String.valueOf(countryId));
			}
			if (jsonObject.getInteger("cityId") != null) {
				List<Area> cityAreas = areaService.findByProperty("areaId", jsonObject.getInteger("cityId"));
				company.setCity(cityAreas.get(0).getAreaName());
			}
			if (jsonObject.getInteger("provinceId") != null) {
				List<Area> provinceAreas = areaService.findByProperty("areaId", jsonObject.getInteger("provinceId"));
				company.setProvince(provinceAreas.get(0).getAreaName());
			}
			if ("add".equals(type)) {
				company.setCompanyId(autoCodeSeedService.GetNewID("companyId"));
				company.setCreateDate(new Date());
				company.setParentCompanyId(1);
				// 客户公司isMain默认设为0
				company.setIsMain(0);
				company.setKind(0);
				save(company);
				json = JsonUtil.getSuccess("添加成功");
			} else {
				updateById(company);
				json = JsonUtil.getSuccess("更新成功");
			}

		}

		return json;
	}

	/**
	 * 多条件等值查询并且忽略自己
	 *
	 * @param propertyNames 属性名数组
	 * @param values        属性值数组
	 * @return 满足条件的所有记录
	 */
	public List<Company> findByPropertiesNotSelf(String[] propertyNames, Object[] values,Integer companyId) {

		QueryWrapper<Company> wrapper = new QueryWrapper<>();
		propertyNames = ConvertUtil.humpToLines(propertyNames);
		if (propertyNames != null) {
			for (int i = 0; i < propertyNames.length; i++) {
				if (values[i] != null) {
					wrapper.eq(propertyNames[i], values[i]);
				} else {
					wrapper.isNull(propertyNames[i]);
				}
			}
		}
		if(companyId!=null){
			wrapper.notIn("company_id",companyId);
		}
		return list(wrapper);
	}


	public JSONObject loadGridVue(PageParam ps) {
		Map<String, Object> params=ps.params;

		List<Company> lists = null;
		JSONObject json = new JSONObject();
		JSONArray jarr = new JSONArray();
		params.put("isDelete", 0);
		Integer kind= (Integer) ps.getParams().get("kind");
		if (kind == null) {
			kind=0;
		}
		params.put("kind", kind);
		int currentPage =ps.getCurrentPage();
		int pageSize =ps.getPageSize();
		IPage<Company> iPage= findPageVue(currentPage, pageSize, params, new String[] {"companyName"}, new String[] {"isDelete","kind" }, null,null);
		lists=iPage.getRecords();
		if(lists != null && lists.size() > 0) {
			for (Company company : lists) {
				if(company.getCompanyId()!=1) {
					Map<String, Object> mobj = new HashMap<String, Object>();
					mobj.put("companyId", company.getCompanyId());
					mobj.put("companyName", company.getCompanyName());
					mobj.put("province", company.getProvince());
					mobj.put("city", company.getCity());
					mobj.put("country", company.getCountry());
					if(company.getAreaCode()!=null){
						String areaCode = company.getAreaCode();
						mobj.put("countryId", Integer.valueOf(areaCode));
						mobj.put("cityId", Integer.valueOf(areaCode.substring(0, 4)+"00"));
						mobj.put("provinceId", Integer.valueOf(areaCode.substring(0, 3)+"000"));
					}
					mobj.put("fullAddress", company.getFullAddress());
					mobj.put("webUrl", company.getWebUrl());
					mobj.put("post", company.getPost());
					mobj.put("introduce", company.getIntroduce());
					jarr.add(mobj);
				}
			}
		}
		json.put(APP.DATA, jarr);
		json.put(APP.TOTAL_COUNT, iPage.getTotal());
		json.put(APP.POS, (currentPage - 1) * pageSize);
		json.put(APP.CURRENT_PAGE, iPage.getCurrent());
		return json;
	}
	public JSONObject deleteVue(JSONObject jsonObject){
		JSONObject json;
		if(jsonObject.getInteger("companyId")!=null){
			Company company = new Company();
			company.setCompanyId(jsonObject.getInteger("companyId"));
			company.setIsDelete(1);
			updateById(company);
			json = JsonUtil.getSuccess("删除成功!");
		}else{
			json = JsonUtil.getFail("删除失败,请选择要删除的数据");
		}
		return json;
	}







}
